var RoleManger = function(){
	var userGridObj=null;
	var roleTreeObj = null;
	var addedPermission = {};
	var deledPermission = {};
	var isSelected = false;
	var roleValidator = null;
	function initRoleTree(id){
		SysRoleController.getAllRoleTreeById(function(trees){
			ZtreeUtil.initTree("ztree",trees,{
				onClick:function(event, treeId, treeNode){
					if(treeNode.type == "role"){
						roleViewShow();
						roleInfoView(treeNode.id);
					}else{
						return false;
					}
				},
				beforeClick:function(treeId, treeNode, clickFlag){
					if(treeNode.type == "role"){
						return true;
					}else{
						return false;
					}
				}
			},{
				data:{
					key:{
						name: "text",
		    			url: null
					}
				}
			},{
				context:[{
	                id: "addRole",
	                label: "新增角色",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="app"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
	        			roleEditShow();
	        			$("#appId").val(NODE.id);
	                }
	            }, {
	                id: "modifyRole",
	                label: "修改角色",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="role"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
	                	loadRoleInfoForEdit(NODE.id);
	                }
	            },{
	                id: "delRole",
	                label: "删除角色",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="role"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
	        			Message.confirm('确认删除角色【'+NODE.text+'】吗？', function(index){
	        				SysRoleController.removeRoleById(NODE.id,function(value){
	        					if(value){
	        						Message.success("删除成功！");
	        						ZtreeUtil.removeNodeRefreshTree('ztree',NODE);
	        						$("#role-info-edit").hide();
	        						$("#role-info-view").hide();
	        					}else{
	        						Message.error("删除失败！");
	        					}
	        				});
	        				Message.close(index); 
	                    });
	        		
	                }
	            }]
			});
			
			roleTreeObj = ZtreeUtil.getZtreeObj('ztree');
			if(id != ""){
				var node = roleTreeObj.getNodeByParam("id",id);
				roleTreeObj.selectNode(node);
			}
			
		});
	}
	
	//tab-------------------------------------------
	
	function roleViewShow(){
		$("#role-info-view").show();
		$("#role-info-edit").hide();
		
	}
	function roleEditShow(){
		AppUtils.clearForm("#editRoleForm");
		$('#roleEditTab a:first').tab('show');
		$("#role-info-edit").show();
		$("#role-info-view").hide();
	}
	
	function clearPermissionList() {
		addedPermission = {};
		deledPermission = {};
		jQuery("#permissionColumnList").empty();
		jQuery("#addPermissionColumnList").empty();
		jQuery("#delPermissionColumnList").empty();
		jQuery("#permissionColumnListView").empty();
	
	}
	
	function roleInfoView(roleId){
		$("#role-view-info").click();
		SysRoleController.getRoleInfoById(roleId,function(retMap){
			clearPermissionList();
			var roleInfo = retMap["roleDTO"];
			var permissionList = retMap["permissionList"];
			$.each(roleInfo, function(key, value) {
				if(key !="appId" && key!="url"){
					dwr.util.setValue('view_' + key, value);
				}
			});
			showOwnPermissionView(permissionList);
			
		});
		if(userGridObj == null){
			userGridObj = $.fn.bsgrid.init('has-user-table', {
	            url:contextPath+"/sys/role/roleHasUsers.htm",
	            otherParames:{"roleId":roleId},
	            pageSizeSelect: true,
	            stripeRows: true,
	            rowSelectedColor:false,
	            pageSize: 10
	        });
		}else{
			userGridObj.search({"roleId":roleId});
		}
		
	}
	function loadRoleInfoForEdit(roleId,tabId){
		AppUtils.validatorRemoteCache("#name");
		roleEditShow();
		SysRoleController.getRoleInfoById(roleId,function(retMap){
			if(retMap){
				clearPermissionList();
				var roleInfo = retMap["roleDTO"];
				var permissionList = retMap["permissionList"];
				dwr.util.setValues(roleInfo);
				showOwnPermission(permissionList);
				
				if(tabId){
					$("#"+tabId).click();
				}
			}
		});
	}
	function showOwnPermissionView(permissionInfos){
		var ownPermissionStr = "";
		$.each(permissionInfos,function(index,element){
			if($("#"+element.id).length == 0){
				ownPermissionStr += "<li id=\"own_"+element.id+"\">" +element.name+
				"</li>"
			}
		});
		$("#permissionColumnListView").append(ownPermissionStr);
		
	}
	function showOwnPermission(permissionInfos){
		var ownPermissionStr = "";
		$.each(permissionInfos,function(index,element){
			if($("#"+element.id).length == 0){
				ownPermissionStr += "<li id=\"own_"+element.id+"\">" +element.name+
				"<input type=\"button\" class=\"button-delete\" onclick=\"RoleManger.removeOwnedPermission(\'"+element.id+"\',\'"+element.name+"\');\"></li>"
			}
		});
		$("#permissionColumnList").append(ownPermissionStr);
		
	}
	
	function addPermissionColumnList(nodes){
		var addPermissionStr = "";
		$.each(nodes,function(index,element){
			if(addedPermission[element.id] != 1){
				addedPermission[element.id] = 1;
				addPermissionStr += "<li id=\""+element.id+"\">" +
				"<input type=\"hidden\" name=\"addPermissionId\" value=\""+element.id+"\">" +element.text+
				"<input type=\"button\" class=\"button-delete\" onclick=\"RoleManger.removeAddedPermission(\'"+element.id+"\');\"></li>"
			}
		});
		
		$("#addPermissionColumnList").append(addPermissionStr);
	}
	
	//save --------------------------------
	function saveRoleInfo(){
		roleValidator.form();
		if (!roleValidator.valid()) {
			return false;
		}
		var roleInfo = dwr.util.getFormValues('editRoleForm');
		SysRoleController.saveRoleBaseInfo(roleInfo,function(roleInfoDTO){
			if(roleInfoDTO){
				$("#id").val(roleInfoDTO.id);
				Message.success("保存成功!");
				initRoleTree(roleInfoDTO.id);
			}
		});
	}
	
	function savePermission(){
		var roleId = $("#id").val();
		var addPermissions= getValuesByName('addPermissionId');
		var delPermissions = getValuesByName('delPermissionId');
		SysRoleController.savePermissionRelation(roleId,addPermissions,delPermissions,function(message){
			if(message == "保存成功"){
				Message.success(message);
				loadRoleInfoForEdit(roleId,'role-edit-permission');
			}else{
				Message.error(message);
			}
		});
		
		
	}
	
	//user--------------------------------------
	
	function removeRoleHasUser(roleId,userId){
		SysRoleController.deleteUserWithRoleRelation(roleId,userId,function(data){
			if(data){
				Message.success("成功！");
				userGridObj.refreshPage();
			}
		});
	}
	function addRoleHasUser(roleId,userName){
		SysRoleController.addUserWithRoleRelation(roleId,userName,function(data){
			if(data){
				Message.success("成功！");
				userGridObj.refreshPage();
			}else{
				Message.error("失败！");
			}
		});
	}
	
	return{
		initRoleView:function(){
			initRoleTree();
			$('#roleTab a:first').tab('show');
			$('#roleEditTab a:first').tab('show');
			
			roleValidator = $("#editRoleForm").validate({
				onkeyup: function(element, event){
					if ($(element).attr('name') == "name") {
                        return false; 
                    } else { 
                        if ( event.which === 9 && this.elementValue( element ) === "" ) {
                            return;
                        } else if ( element.name in this.submitted || element === this.lastElement ) {
                            this.element( element );
                        }
                    }
				},
				rules:{
					name:{required:true,maxlength:10,remote:{
						url:contextPath+'/sys/role/checkNameISExist.htm',
						type:'post',
						cache:false,
						dataType:'json',
						data:{
							id:function(){
								return $("#id").val();
							},
							appId:function(){
								return $("#appId").val();
							}
						}
					}},
					sort:{required:true,maxlength:3,digits:true},
					code:{required:true,maxlength:40}
				},
				messages:{
					name:{remote:jQuery.format("角色名称【{0}】已经存在")}
				}
			});
			
			$("#role-edit-permission").click(function(){
				if($("#id").val() == ""){
					$('#role-edit-permission').one('shown', function (e) {
						$("#tabs-role-edit-permission").removeClass("active");
					});
					Message.tips("请先保存角色基本信息","#role-edit-permission",{layout:'right'});
				}else{
					$("#tabs-role-edit-permission").addClass("active");
				}
				
			});
			
			
			jQuery("#username4AddRole").keyup(function(){
				isSelected = false; 
			});
			$("#username4AddRole").typeahead({
				source: function (query, process) {
					$.ajax({
						url:contextPath+"/sys/role/loadUsers.htm",
						dataType:'json',
						type:'post',
						data:{"term":query},
						success:function(data){
							process(data);
						}
					});
				},
				items:10,
				updater:function(item){
					isSelected = true;
					return item;
				}
			});
			
		},
		refreshTree:function(id){
			initRoleTree(id);
		},
		submitRoleInfoForm:function(){
			saveRoleInfo();
		},
		loadRoleInfo4Edit:function(roleId,tabId){
			loadRoleInfoForEdit(roleId,tabId);
		},
		addUserOpen:function(){
			DialogUtils.innerDialog({
			    title: '添加人员',
			    area: ['350px', '200px'],
			    fix: true, //不固定
			    move:false,
			    zIndex:900,
			    maxmin: false,
			    content: $("#addUserRole"),
			    success: function(layero, index){
			    	$("#layui-layer"+index).height(160);
			    	$("#username4AddRole").val("");
			    	isSelected=false;
			    	$("#layerIndex").val(index);
			    }
			});
		},
		saveUserWithRole:function(){
			var value = $("#username4AddRole").val();
	    	if(value == ""){
	    		Message.tips("请输入添加的用户名或姓名，然后从下拉列表中选取用户名","#username4AddRole",{layout:'right'});
	    		return false;
	    	}
	    	if(!isSelected){
	    		Message.tips("请从提示的下拉列表中选取用户名",".layui-layer-btn0",{layout:'right'});
	    		return false;
	    	}
	    	DialogUtils.close($("#layerIndex").val());
			addRoleHasUser($("#view_id").val(),value.substring(0,value.indexOf("(")));
		},
		removeRoleHasUserOpeate:function(record, rowIndex, colIndex, options){
			return '<a href="#" onclick="RoleManger.removeRoleHasUser(\''+$("#view_id").val()+'\',\''+userGridObj.getRecordIndexValue(record, 'userId')+'\');">删除</a>';
		},
		removeRoleHasUser:function(roleId,userId){
			removeRoleHasUser(roleId,userId);
		},
		selectPermission:function(){
			initPermissionChoiceTree();
			DialogUtils.innerDialog({
				area: ['300px', '500px'],
			    title: '选择权限',
			    content:$("#perimssionTreePage"),
			    btn: ['选择', '关闭'],
			    yes: function(index, layero){
			    	addPermissionColumnList(getSelectedNodes());
			    	DialogUtils.close(index);
			    },cancel: function(index){
			    }
				
			});
		},
		removeAddedPermission:function(permissionId){
			$("#"+permissionId).remove();
			addedPermission[permissionId] = 0;
		},
		removeOwnedPermission:function(permissionId,permissionText){
			if (deledPermission[permissionId] != 1) {
				deledPermission[permissionId] = 1;
				$("#own_"+permissionId).hide();
				var delPermissionStr ="";
				delPermissionStr = "<li id=\""+permissionId+"\">" +
				"<input type=\"hidden\" name=\"delPermissionId\" value=\""+permissionId+"\">" +permissionText+
				"<input type=\"button\" class=\"button-delete\" onclick=\"RoleManger.removeDelPermission(\'"+permissionId+"\');\"></li>";
				$("#delPermissionColumnList").append(delPermissionStr);
			}
			
		},
		removeDelPermission:function(permissionId){
			jQuery("#" + permissionId).remove();
			jQuery("#own_" + permissionId).show();
			deledPermission[permissionId] = 0;
			
		},
		savePermissionCheck:function(){
			savePermission();
		}
	}
	
}();